package org.idea.spring.task.config;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

import static org.idea.spring.task.config.SqlSessionConfig.FILE_NAME;

/**
 * @author idea
 * @data 2018/9/24
 */
public class SqlSessionUtil {

    private static SqlSessionFactory sqlSessionFactory;
    private static SqlSession sqlSession;

    static {
        String filePath = FILE_NAME;
        InputStream in = null;
        try {
            in = Resources.getResourceAsStream(filePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        sqlSessionFactory = (new SqlSessionFactoryBuilder()).build(in);
    }


    public static SqlSession getSqlSession() {
        if (sqlSession != null) {
            sqlSession.close();
        }
        return sqlSessionFactory.openSession();
    }
}
